package com.irdstudio.apicenter.gateway.web.controller;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;

import com.irdstudio.apicenter.gateway.comm.MaccsPacket;
import com.irdstudio.apicenter.gateway.core.jdbc.MaccsBaseDAO;
import com.irdstudio.apicenter.gateway.util.spring.BeanUtils;
import com.irdstudio.apicenter.gateway.web.MaccsException;
import com.irdstudio.apicenter.gateway.web.MaccsTradeDefineVo;
import com.irdstudio.apicenter.gateway.web.view.JsonView;
import com.irdstudio.apicenter.gateway.web.view.View;

/**
 * 比对移动客户端版本号是否为是最新
 * 
 * @author zs.ligm
 * @version 1.0
 * @date 2015-07-24
 */
/**
 * @author fmf
 *
 */
@Controller
public class CheckAppVersion implements IController {

	/* 文本日志输出 */
	private static final Logger logger = LoggerFactory.getLogger(CheckAppVersion.class);

	@Override
	public View execute(MaccsTradeDefineVo tradeDefine, MaccsPacket inPacket, HttpServletRequest request,
			HttpServletResponse response) throws MaccsException {

		// 接收移动客户端传过来的参数
		String appId = inPacket.getValue("appId");
		// 移动端当前的版本号
		String appVersion = inPacket.getValue("app_version");
		/**
		 * 处理部分客户端带v的版本号，去掉，因为苹果发布ipa不支持带字符的版本号而之前部分安卓带v
		 */
		if (appVersion.contains("v")) {
			if (appVersion.contains("v")) {
				int index = appVersion.indexOf("v");
				appVersion = appVersion.substring(index + 1, appVersion.length());
			}
		}
		// 获取服务端最新版本号
		MaccsBaseDAO jdbcDao = BeanUtils.getBean(MaccsBaseDAO.class);
		String serverAppVersion = jdbcDao.getJdbcTemplate().queryForObject(
				"select app_version_id from app_base_info where app_id=?", new Object[] { appId }, String.class);

		serverAppVersion = serverAppVersion == null ? "" : serverAppVersion;

		// 比对版本，确定是否需要升级
		MaccsPacket outPacket = null;
		/**
		 * 客户端版本高，返回正数，客户端版本低，返回负数，一样返回0
		 */
		int result = compareVersion(appVersion,serverAppVersion);
		
		logger.debug("客户端版本:" + appVersion + "服务端版本:" + serverAppVersion);
		if (result < 0) {
			// 说明需要升级,获取升级地址
			Map<String, Object> serverVersion = jdbcDao.queryForMap(
					"select * from app_version where app_id=? and app_version_id=?",
					new Object[] { appId, serverAppVersion });
			// 如果没有取到版本发布记录，说明不需要升级
			if (serverVersion != null) {
				outPacket = new MaccsPacket(serverVersion);
				// 日志记录返回的数据
				logger.debug("客户端serverVersion:" + serverVersion.toString());
			} else {
				outPacket = new MaccsPacket();
			}
		} else {
			outPacket = new MaccsPacket();
		}

		outPacket.addVariable("ec", 0);
		outPacket.addVariable("em", "");

		return new JsonView(request, response, outPacket);
	}

	/**
	 * 比较版本号的大小,客户端大则返回一个正数,服务端大返回一个负数,相等则返回0
	 * 
	 * @param clientVersion
	 * @param serverVersion
	 * @return
	 */
	public static int compareVersion(String clientVersion, String serverVersion) {

		String[] clientVersionArray = clientVersion.split("\\.");// 注意此处为正则匹配，不能用"."；
		String[] serverVersionArray = serverVersion.split("\\.");
		int idx = 0;
		int minLength = Math.min(clientVersionArray.length, serverVersionArray.length);// 取最小长度值
		int diff = 0;
		while (idx < minLength && (diff = clientVersionArray[idx].length() - serverVersionArray[idx].length()) == 0// 先比较长度
				&& (diff = clientVersionArray[idx].compareTo(serverVersionArray[idx])) == 0) {// 再比较字符
			++idx;
		}
		// 如果已经分出大小，则直接返回，如果未分出大小，则再比较位数，有子版本的为大；
		diff = (diff != 0) ? diff : clientVersionArray.length - serverVersionArray.length;
		return diff;
	}
}
